import React from 'react'
import { connect } from 'react-redux'
import { push } from 'connected-react-router'
import { Query } from 'react-apollo'
import getItemId from 'graphql/getItemId.graphql'
import { global as globalDuck } from 'ducks'
import Loading from './loadingItem'

const ItemPage = ({
  pid, user, lableState, link, match,
}) => {
  const getlabelState = lableState === 'all' ? ['label', 'done'] : [lableState]
  const order = lableState === 'done' ? { finish_time: 'desc' } : { create_at: 'asc' }
  return (
    <Query
      query={getItemId}
      variables={{
        projectId: pid,
        userId: user.id,
        state: getlabelState,
        order,
      }}
      fetchPolicy="network-only"
      onCompleted={(data) => {
        if (data.project_task_item.length > 0) {
          link(`${match.url}/${data.project_task_item[0].id}`)
        } else {
          link(`${match.url}/nodata`)
        }
      }}
    >
      {({ loading, error, data }) => {
        if (loading) return <Loading />
        if (error) return `Error! ${error.message}`
        return null
      }}
    </Query>
  )
}

const mapStateToProps = state => ({
  user: globalDuck.selectors.user(state),
})

const mapDispatchToProps = {
  link: push,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(ItemPage)
